package bid.yanhj.common.util;

import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import bid.yanhj.common.service.FormatService;

/**
 * bean装map类.
 * @author yanhaijiang
 *
 */
public class BeanUtil {
    private static final Logger LOG = LoggerFactory.getLogger(BeanUtil.class);
    
    /**
     * 利用Introspector和PropertyDescriptor 将Bean --> Map.
     * 
     * @param obj 对象.
     * @return
     */
    public static Map<String, Object> transBean2Map(Object obj) {
    	
        if (obj == null) {
            return null;
        }
        
        Map<String, Object> map = new HashMap<String, Object>();
        
        try {
			BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
			PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
			for (PropertyDescriptor property : propertyDescriptors) {
				String key = property.getName();
				
				// 过滤class属性
				if (!key.equals("class")) {
                    // 得到property对应的getter方法
                    Method getter = property.getReadMethod();
                    Object value = getter.invoke(obj);

                    map.put(key, value);
				}
			}
		} catch (IntrospectionException e) {
			LOG.error(FormatService.logFormat("IntrospectionException"), e);
		} catch (IllegalAccessException e) {
			LOG.error(FormatService.logFormat("IllegalAccessException"), e);
		} catch (IllegalArgumentException e) {
			LOG.error(FormatService.logFormat("IllegalArgumentException"), e);
		} catch (InvocationTargetException e) {
			LOG.error(FormatService.logFormat("InvocationTargetException"), e);
		}
        
		return map;
    }
}
